﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;

namespace B.MESUI.Login.BasicData_UI
{
    public partial class AddProjectLineForm : DevExpress.XtraEditors.XtraForm
    {
        public event EventHandler AddSuccess;
        private List<string> allWorkshops = new List<string>();
        private Dictionary<string, string> workshopNameIdMap = new Dictionary<string, string>();
        public AddProjectLineForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Load += AddProjectLineForm_Load;
            comboBoxEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
            comboBoxEdit1.Properties.AutoComplete = false;
            comboBoxEdit1.EditValueChanged += comboBoxEdit1_EditValueChanged;
        }

        private async void AddProjectLineForm_Load(object sender, EventArgs e)
        {
            await LoadWorkShopList();
        }

        private async Task LoadWorkShopList()
        {
            string url = "http://39.103.49.30:9982/api/WorkShop/GetAll";
            using (var client = new System.Net.Http.HttpClient())
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    var list = result.resultData;
                    comboBoxEdit1.Properties.Items.Clear();
                    allWorkshops.Clear();
                    workshopNameIdMap.Clear();
                    foreach (var item in list)
                    {
                        string id = item.id == null ? "" : item.id.ToString();
                        string name = item.workshoP_NAME == null ? "" : item.workshoP_NAME.ToString();
                        allWorkshops.Add(name);
                        comboBoxEdit1.Properties.Items.Add(name);
                        if (!workshopNameIdMap.ContainsKey(name))
                            workshopNameIdMap.Add(name, id);
                    }
                }
            }
        }
        private void comboBoxEdit1_EditValueChanged(object sender, EventArgs e)
        {
            string keyword = comboBoxEdit1.Text.Trim();
            comboBoxEdit1.Properties.Items.Clear();
            foreach (var item in allWorkshops)
            {
                if (string.IsNullOrEmpty(keyword) || item.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    comboBoxEdit1.Properties.Items.Add(item);
                }
            }
            comboBoxEdit1.ShowPopup();
        }

        private async void Addbutton1_Click(object sender, EventArgs e)
        {
            var lineCode = textEdit1.Text.Trim();
            var lineName = textEdit2.Text.Trim();
            var workshopName = comboBoxEdit1.Text.Trim();
            var description = textEdit4.Text.Trim();

            string workshopId = "";
            if (workshopNameIdMap.ContainsKey(workshopName))
                workshopId = workshopNameIdMap[workshopName];

            var data = new
            {
                linE_CODE = lineCode,
                linE_NAME = lineName,
                workshoP_ID = workshopId,
                workshoP_NAME = workshopName,
                linE_DESCRIPTION = description
            };

            using (var client = new System.Net.Http.HttpClient())
            {
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                var content = new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json");
                var response = await client.PostAsync("http://39.103.49.30:9982/api/ProjectLine/AddProductionLine", content);
                if (response.IsSuccessStatusCode)
                {
                    var respStr = await response.Content.ReadAsStringAsync();
                    var respObj = Newtonsoft.Json.Linq.JObject.Parse(respStr);
                    if (respObj["code"]?.ToString() == "200")
                    {
                        MessageBox.Show("添加成功！");
                        AddSuccess?.Invoke(this, EventArgs.Empty);
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("添加失败：" + respObj["message"]);
                    }
                }
                else
                {
                    MessageBox.Show("网络错误，添加失败！");
                }
            }
        }
    }
}